package com.skwyb.form.service.system;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skwyb.form.bean.dto.SysDictEntry;
import com.skwyb.form.bean.dto.SysDictType;
import com.skwyb.form.core.BusinessException;
import com.skwyb.form.mapper.SysDictEntryMapper;
import com.skwyb.form.utils.AssertUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Log4j2
@Service
public class DictEntryService extends ServiceImpl<SysDictEntryMapper, SysDictEntry> {

    @Autowired
    private DictTypeService typeService;

    public Integer saveDict(SysDictEntry record) throws BusinessException {
        Integer result = 0;
        SysDictType type = typeService.getById(record.getDictTypeId());
        AssertUtils.isNull(type, "分类不存在");

        saveOrUpdate(record);
        log.info("==> save DictEntry execute success {} row", result);
        return result;
    }

    @CacheEvict(value = "dictEntry", key = "#entity.id", beforeInvocation = true)
    @Override
    public boolean saveOrUpdate(SysDictEntry entity) {
        return super.saveOrUpdate(entity);
    }

    @CacheEvict(value = "dictEntry", key = "#id", beforeInvocation = true)
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }


    @Cacheable(value = "dictEntry", key = "#typeId")
    public List<SysDictEntry> selectByType(String typeId) {
        return super.list(Wrappers.lambdaQuery(new SysDictEntry().setDictTypeId(typeId)));
    }

    public String selectByCode(String typeId, String code) {
        List<SysDictEntry> entryList = selectByType(typeId);
        for (SysDictEntry d : entryList) {
            if (code.equalsIgnoreCase(d.getDictCode())) {
                return d.getDictName();
            }
        }
        return StringUtils.EMPTY;
    }
}